package com.css.upms.biz.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.css.common.core.utils.R;
import com.css.upms.api.entity.SysUserDept;
import com.css.upms.biz.mapper.SysUserDeptMapper;
import com.css.upms.biz.service.SysUserDeptService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户数据权限关系
 *
 * @author hanyx
 * @date 2019-05-16 09:48:48
 */
@Service("sysUserDeptService")
@AllArgsConstructor
public class SysUserDeptServiceImpl extends ServiceImpl<SysUserDeptMapper, SysUserDept> implements SysUserDeptService {

    /**
     * 用户-数据权限设置
     *
     * @param userId
     * @param deptIds
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveUserDepts(String userId, String deptIds) {
        if (StringUtils.isBlank(userId) ) {
            return Boolean.FALSE;
        }
        this.remove(Wrappers.<SysUserDept>query().lambda()
                .eq(SysUserDept::getUserId, userId));

        if (StringUtils.isBlank(deptIds) ) {
            return Boolean.FALSE;
        }
        List<SysUserDept> userDeptList = Arrays
                .stream(deptIds.split(","))
                .map(deptId -> {
                    SysUserDept userDept = new SysUserDept();
                    userDept.setUserId(userId);
                    userDept.setDeptId(String.valueOf(deptId));
                    return userDept;
                }).collect(Collectors.toList());

        return this.saveBatch(userDeptList);
    }
}
